<template>
  <div class="vehicle-entry-exit-application bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">车辆出入申请</h2>

    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchApplications" @reset="resetSearch" />
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <el-button type="primary" @click="openAddDialog">申请</el-button>
      <el-button type="danger" @click="deleteSelected">删除</el-button>
      <!--  <button @click="openImportDialog" class="btn btn-secondary">导入</button> -->
      <el-button @click="exportData(applications, '车辆申请', selectedIds)">导出</el-button>
    </div>

    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedApplications" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="LICENSE_PLATE" label="车牌号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="VEHICLE_TYPE" label="车辆类型" header-align="center" align="center"></el-table-column>
        <el-table-column prop="LICENSE_PLATE_COLOR" label="车牌颜色" header-align="center" align="center"></el-table-column>
        <el-table-column prop="COMPANY_CODE" label="所属企业编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DRIVER_NAME" label="驾驶员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DRIVER_ID_CARD" label="证件号" header-align="center" align="center"></el-table-column>
        <el-table-column prop="TRANS_STATUS" label="运货状态" header-align="center" align="center"></el-table-column>
        <el-table-column prop="CREATED_DATE" label="提交时间" header-align="center" align="center">
          <template #default="scope">
            <div>{{ dayjs(scope.row.CREATED_DATE).format('YYYY-MM-DD HH:mm:ss') }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="APPLICATION_STATUS" label="申请状态" header-align="center" align="center">
          <template #default="scope">
            <div :class="getStatusClass(scope.row.APPLICATION_STATUS)">
              {{ scope.row.APPLICATION_STATUS }}
            </div>
          </template>

        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button v-if="scope.row.APPLICATION_STATUS == '已提交'" type="primary" size="small"
              @click="editApplication(scope.row)" link>编辑</el-button>
            <el-button type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- Pagination -->
    <Pagination v-if="applications.length" :tableData="applications" @alltabledata="alltabledata" />
    <!-- Add/Edit Dialog -->
    <el-dialog class="dialog-from" v-model="isDialogOpen" :title="isEditing ? '编辑申请' : '新增申请'" width="650"
      destroy-on-close align-center>
      <form>
        <!-- 基本信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>基本信息</span>
          </div>
          <div class="grid grid-cols-3 gap-4">

            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">车牌号码：</label>
              <el-input type="text" id="licensePlate" v-model="formData.LICENSE_PLATE" required class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">车辆类型：</label>
              <el-select v-model="formData.VEHICLE_TYPE" class="set-select" placeholder="请选择">
                <el-option label="普货车" value="普货车" />

                <el-option label="社会车辆" value="社会车辆" />
                <el-option label="其他" value="其他" />
              </el-select>
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">车牌颜色：</label>
              <el-select v-model="formData.LICENSE_PLATE_COLOR" class="set-select" placeholder="请选择">
                <el-option label="黄色" value="黄色" />
                <el-option label="蓝色" value="蓝色" />
                <el-option label="绿色" value="绿色" />
              </el-select>
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">所属运输企业编码：</label>
              <el-input type="text" id="licensePlate" v-model="formData.COMPANY_CODE" class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">货运状态：</label>
              <el-select v-model="formData.TRANS_STATUS" class="set-select" placeholder="请选择">
                <el-option label="供货" value="供货" />
                <el-option label="提货" value="提货" />
              </el-select>
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">前往企业：</label>
              <el-input type="text" id="licensePlate" v-model="formData.TRANSPORT_COMPANY" required class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">预计入园时间：</label>
              <input type="datetime-local" id="submissionTime" class='clatime ' v-model="formData.IN_AT" required />
            </div>

            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">预计出园时间：</label>
              <input type="datetime-local" id="submissionTime" class='clatime ' v-model="formData.EXIT_AT" required />
            </div>
          </div>
        </div>
        <!-- 驾驶员信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>驾驶员信息</span>
          </div>
          <div class="grid grid-cols-3 gap-4">
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">驾驶员姓名：</label>
              <el-input type="text" id="licensePlate" v-model="formData.DRIVER_NAME" required class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">证件号码：</label>

              <el-input type="text" id="licensePlate" v-model="formData.DRIVER_ID_CARD" required class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">联系方式：</label>
              <el-input type="text" id="licensePlate" v-model="formData.PHONE_NUMBER" required class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">驾驶证：</label>
              <!-- <input type="text" id="licensePlate" v-model="formData.DRIVING_LICENSE" required class="input" /> -->

              <div v-if="isEditing" style="margin:10px 0">
                <span v-for="item in imgdata" :key="item">
                  <el-image style="width: 100px; height: 100px" lazy :src="item" :zoom-rate="1.2" :max-scale="7"
                    :min-scale="0.2" :initial-index="0" fit="cover" />
                </span>
              </div>
              <input type="file" id="importFile" @change="handleRISK_HAS" class="mt-1 block w-full" />
            </div>
            <div>
              <label for="licensePlate">有效期起：</label>
              <input type="datetime-local" id="submissionTime" class='clatime ' v-model="formData.LEN_START_DATE"
                required />
            </div>
            <div>
              <label for="licensePlate">有效期止：</label>
              <input type="datetime-local" id="submissionTime" class='clatime ' v-model="formData.LEN_END_DATE"
                required />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">是否有效：</label>
              <el-select v-model="formData.WHETHER_LEN" class="set-select" placeholder="请选择">
                <el-option label="有效" value="有效" />
                <el-option label="无效" value="无效" />
              </el-select>
            </div>

          </div>
        </div>
        <!-- 其他信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>其他信息</span>
          </div>
          <div>
            <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">备注：</label>
            <el-input type="text" id="licensePlate" v-model="formData.STAMP" required class="input" />
          </div>
        </div>
        <div class="mt-6 flex justify-end space-x-2">
          <el-button @click="closeDialog">取消</el-button>
          <el-button @click="handleSubmit" type="primary">提交</el-button>
        </div>
      </form>
    </el-dialog>
    <!-- View Details Dialog -->
    <el-dialog class="dialog-from" v-model="isViewDialogOpen" title="查看申请详情" width="650" destroy-on-close align-center>


      <div class="tablename">
        <div
          style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
        </div>
        <span>基本信息</span>
      </div>
      <div class="grid grid-cols-3 gap-4">
        <div><strong>系统单号：</strong>{{ viewingItem.ID }}</div>
        <div><strong>车牌号码：</strong>{{ viewingItem.LICENSE_PLATE }}</div>
        <div><strong>车辆类型：</strong>{{ viewingItem.VEHICLE_TYPE }}</div>
        <div><strong>车牌颜色：</strong>{{ viewingItem.LICENSE_PLATE_COLOR }}</div>
        <div><strong>所属运输企业编码：</strong>{{ viewingItem.COMPANY_CODE }}</div>
        <div><strong>货运状态：</strong>{{ viewingItem.TRANS_STATUS }}</div>
        <div><strong>前往企业：</strong>{{ viewingItem.TRANSPORT_COMPANY }}</div>
        <div><strong>预计入园时间：</strong>{{ formatDateTime(viewingItem.IN_AT) }}</div>
        <div><strong>预计出园时间：</strong>{{ formatDateTime(viewingItem.EXIT_AT) }}</div>
      </div>
      <div class="tablename">
        <div
          style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
        </div>
        <span>驾驶员信息</span>
      </div>
      <div class="grid grid-cols-3 gap-4">
        <div><strong>驾驶员姓名：</strong>{{ viewingItem.DRIVER_NAME }}</div>
        <div><strong>证件号码：</strong>{{ viewingItem.DRIVER_ID_CARD }}</div>
        <div><strong>联系方式：</strong>{{ viewingItem.PHONE_NUMBER }}</div>
        <div><strong>驾驶证：</strong>
          <div v-if="viewingItem.DRIVING_LICENSE == null">
            {{ viewingItem.DRIVING_LICENSE }}
          </div>

          <span v-else v-for="item in imgdata" :key="item">
            <el-image style="width: 100px; height: 100px" lazy :src="item" :zoom-rate="1.2" :max-scale="7"
              :min-scale="0.2" :initial-index="0" fit="cover" />
          </span>

        </div>
        <div><strong>有效期起：</strong>{{ formatDateTime(viewingItem.LEN_START_DATE) }}</div>
        <div><strong>有效期止：</strong>{{ formatDateTime(viewingItem.LEN_END_DATE) }}</div>
        <div><strong>是否有效：</strong>{{ viewingItem.WHETHER_LEN }}</div>
      </div>
      <div class="tablename">
        <div
          style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
        </div>
        <span>其他信息</span>
      </div>
      <div><strong>备注：</strong>{{ viewingItem.STAMP }}</div>
      <div class="mt-6 flex justify-end space-x-2">
        <el-button @click="closeViewDialog">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加导入对话框 -->
    <Teleport to="body">
      <div v-if="isImportDialogOpen"
        class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
        <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[500px]">
          <h3 class="text-lg font-bold mb-4">车辆出入申请</h3>
          <input type="file" @change="handleFileUpload" accept=".xlsx, .xls" class="mb-4 block w-full text-sm text-muted-foreground
            file:mr-4 file:py-2 file:px-4
            file:rounded-full file:border-0
            file:text-sm file:font-semibold
            file:bg-primary file:text-primary-foreground
            hover:file:bg-primary/90" />
          <div class="flex justify-end space-x-2">
            <button @click="closeImportDialog" class="btn btn-secondary">取消</button>
            <!-- <button @click="importData" class="btn btn-primary">导入</button> -->
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, getCurrentInstance } from 'vue'
import axios from 'axios'
import * as XLSX from 'xlsx'
const { proxy } = getCurrentInstance()
import { dayjs } from "element-plus"
import { exportData, checkval } from '#/utils/exportfile.js'
const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/vehicle-entry-exit'
})

const loading = ref(false)
const displayedPlanData = ref([])


const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const rowKey = (row) => row.ID // 设置行的唯一标识

const selectedIds = ref([])

const search = ref({
  LICENSE_PLATE: '',
  DRIVER_NAME: '',
  VEHICLE_TYPE: '',
  APPLICATION_STATUS: ''
})
const handleRISK_HAS = (event) => {
  formData.value.files = []
  const files = Array.from(event.target.files)
  formData.value.files = [files[0]]

}
const formItems = ref([
  {
    label: '车牌号码：',
    model: 'LICENSE_PLATE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '驾驶员姓名：',
    model: 'DRIVER_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '车辆类型：',
    model: 'VEHICLE_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '普货车', value: '普货车' },
      { label: '社会车辆', value: '社会车辆' },
      { label: '其他', value: '其他' },
    ],
  },
  {
    label: '申请状态：',
    model: 'APPLICATION_STATUS',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '已提交', value: '已提交' },
      { label: '未通过', value: '未通过' },
      { label: '通过', value: '通过' },
    ],
  },
])
const table = ref()
const imgdata = ref([])
const applications = ref([])
const selectAll = ref(false)
const isDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const isEditing = ref(false)
const formData = ref({
  files: []
})
const viewingItem = ref(null)
const displayedApplications = ref([])
const alltabledata = (data) => {
  displayedApplications.value = data

}
const searchApplications = async () => {
  displayedApplications.value = []
  try {
    const response = await axios.get(`${apiBaseUrl.value}/application/search`, { params: search.value })
    console.log('搜索结果:', response.data)
    applications.value = response.data.map(app => ({ ...app, selected: false }))
    updateSelectAllState()
  } catch (error) {
    console.error('搜索申请失败:', error)
    alert('搜索申请失败: ' + (error.response?.data?.message || error.message))
  }
}

const resetSearch = () => {
  search.value = {
    LICENSE_PLATE: '',
    DRIVER_NAME: '',
    VEHICLE_TYPE: '',
    APPLICATION_STATUS: ''
  }
  searchApplications()
}

const openAddDialog = () => {
  isDialogOpen.value = true
  isEditing.value = false

}

const closeDialog = () => {
  isDialogOpen.value = false
  formData.value = {
    APPLICATION_TIME: new Date().toISOString().slice(0, 16),
    APPLICATION_STATUS: '已提交',
    files: []
  }
}

const handleSubmit = async () => {

  if (checkval(['LICENSE_PLATE',
    'VEHICLE_TYPE',
    'LICENSE_PLATE_COLOR',
    'TRANS_STATUS',
    'TRANSPORT_COMPANY',
    'IN_AT',
    'EXIT_AT',
    'DRIVER_NAME',
    'PHONE_NUMBER',
    'DRIVER_ID_CARD',
    'LEN_START_DATE',
    'LEN_END_DATE',
    'WHETHER_LEN'], '车辆申请', formData.value)) {
    return
  }

  if (!formData.value.files) {
    alert('驾驶证不能为空')
    return
  }





  const formDataS = new FormData()
  for (const key in formData.value) {
    if (key !== 'files') {
      formDataS.append(key, formData.value[key])
    }
  }
  if (formData.value?.files) {
    formData.value.files.forEach((file, index) => {
      formDataS.append(`files[${index}]`, file)
    })
  }
  try {
    if (isEditing.value) {
      await axios.put(`${apiBaseUrl.value}/application/${formData.value.ID}`, formDataS, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
    } else {
      await axios.post(`${apiBaseUrl.value}/application`, formDataS, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
    }
    alert('提交成功')
    closeDialog()
    await searchApplications()
  } catch (error) {
    console.error('提交申请失败:', error)
    alert('提交申请失败: ' + (error.response?.data?.message || error.message))
  }
}

const deleteSelected = async () => {
  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(item => {
        axios.delete(`${apiBaseUrl.value}/application/${item.ID}`)

      }
      ))
      alert('删除成功')
      selectedIds.value = []
      await searchApplications()
      table.value.clearSelection()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

const editApplication = async (item) => {
  imgdata.value = []
  formData.value = {
    ...item,
    files: []
  }

  formData.value.IN_AT = dayjs(formData.value.IN_AT).format('YYYY-MM-DD HH:mm:ss')
  formData.value.EXIT_AT = dayjs(formData.value.EXIT_AT).format('YYYY-MM-DD HH:mm:ss')
  formData.value.LEN_START_DATE = dayjs(formData.value.LEN_START_DATE).format('YYYY-MM-DD HH:mm:ss')
  formData.value.LEN_END_DATE = dayjs(formData.value.LEN_END_DATE).format('YYYY-MM-DD HH:mm:ss')
  isEditing.value = true
  isDialogOpen.value = true
  if (item.DRIVING_LICENSE) {
    const response = await axios.get(`${apiBaseUrl.value}/download/${item.DRIVING_LICENSE}`)
    imgdata.value.push(response.data.url)
  }
}

const viewDetails = async (item) => {
  imgdata.value = []
  viewingItem.value = item
  isViewDialogOpen.value = true
  if (viewingItem.value.DRIVING_LICENSE) {
    const response = await axios.get(`${apiBaseUrl.value}/download/${viewingItem.value.DRIVING_LICENSE}`)
    imgdata.value.push(response.data.url)
  }
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingItem.value = {}
}

const toggleSelectAll = () => {
  console.log('触发全选:', !selectAll.value)
  selectAll.value = !selectAll.value
  applications.value.forEach(app => {
    app.selected = selectAll.value
    console.log(`设置 ${app.ID} 的选中状态为:`, app.selected)
  })
}

const toggleItemSelection = (item) => {
  console.log('切换选中状态:', item.ID, !item.selected)
  item.selected = !item.selected
  updateSelectAllState()
}

const updateSelectAllState = () => {
  console.log('更新全选状态')
  console.log('当前所有项目的选中状态:', applications.value.map(app => app.selected))
  selectAll.value = applications.value.length > 0 && applications.value.every(app => app.selected)
  console.log('全选状态更新为:', selectAll.value)
}

const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++
}

const getStatusClass = (status) => {
  const classMap = {
    '已提交': 'bg-yellow-100 text-yellow-800',
    '通过': 'bg-green-100 text-green-800',
    '未通过': 'bg-red-100 text-red-800'
  }
  return `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${classMap[status] || ''}`
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

const importFile = ref(null)
const isImportDialogOpen = ref(false)

const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
}

const openImportDialog = () => {
  isImportDialogOpen.value = true
}

const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
}

const importData = async () => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }

  const reader = new FileReader()
  reader.onload = async (e) => {
    const data = new Uint8Array(e.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]
    const jsonData = XLSX.utils.sheet_to_json(worksheet)

    try {
      console.log('导入数据 - 发送数据:', jsonData)
      const response = await axios.post(`${apiBaseUrl.value}/import`, jsonData)
      console.log('导入数据 - 接收到的响应:', response.data)
      alert('数据导入成功')
      closeImportDialog()
      await searchApplications()
    } catch (error) {
      console.error('Error importing data:', error)
      alert('导入数据失败：' + error.message)
    }
  }
  reader.readAsArrayBuffer(importFile.value)
}



// 辅助函数：将字符串转换为ArrayBuffer
function s2ab (s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF
  return buf
}

watch(applications, () => {
  console.log('applications 发生变化')
  console.log('当前数据:', applications.value)
  updateSelectAllState()
}, { deep: true })

watch(selectAll, (newValue) => {
  console.log('selectAll changed:', newValue)
  applications.value.forEach(app => {
    app.selected = newValue
    console.log('watch selectAll - 设置项目状态:', app.ID, app.selected)
  })
})

onMounted(() => {
  searchApplications()
})
</script>

<style scoped>
.input {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.checkbox {
  @apply h-4 w-4 text-primary focus:ring-primary border-input rounded;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.tablename {
  display: flex;
  align-items: baseline;
  margin: 10px 0;
  font-weight: bold;
}
</style>
